package net.telesing.tcmc.back.logic;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.telesing.tcmc.back.dao.DataDao;
import net.telesing.tcmc.back.model.DataModel;
import net.telesing.tcmc.back.model.UserModel;
import net.telesing.tcmc.back.modelqp.DataQp;
import net.telesing.tcmc.common.Constants;
import net.telesing.tcmc.common.DropModel;
import net.telesing.tcmc.common.QueryReturn;
import net.telesing.tcmc.core.utils.FileUtil;
import net.telesing.tcmc.core.web.Ajax;
import net.telesing.tcmc.core.web.AjaxBean;

import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.mvc.upload.TempFile;

/**
 * 资料说明Logic
 *
 * Created by Zmt on 2015/11/10.
 */
@IocBean
public class DataLogic
{
    @Inject
    private DataDao dataDao;

    private static final String NOT_FOUND = "该文件不存在！", FILE_EXIST = "该文件的版本名或版本号重复！";

    /**
     * 分页查询文件
     *
     * @param dataQp
     * @return
     */
    public QueryReturn queryData(DataQp dataQp)
    {
        return dataDao.queryPage(DataModel.class, dataQp);
    }

    /**
     * 根据ID查询文件
     *
     * @param id
     * @return
     */
    public DataModel fetchData(long id)
    {
        return dataDao.fetch(DataModel.class,id);
    }

    /**
     * 新增文件
     *
     * @param dataModel
     * @param uid
     * @return
     */
    public AjaxBean create(DataModel dataModel, long uid)
    {
        AjaxBean result = Ajax.ok();
        try
        {
            if (0 != checkRepeat(dataModel))
                result = Ajax.fail().setMsg(FILE_EXIST);
            else
            {
                String tempPath = dataModel.getPath();
                dataModel.setPath(new FileUtil().getUtil().moveFile(tempPath, Constants.BASE_FILE_URL, false));
                dataDao.insert(dataModel, uid);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            result = Ajax.fail().setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 新增文件
     *
     * @param dataModel
     * @param uid
     * @return
     */
    public AjaxBean modify(DataModel dataModel, long uid)
    {
        AjaxBean result = Ajax.ok();
        try
        {
            DataModel oldModel = dataDao.fetch(DataModel.class, dataModel.getId());
            if (null != oldModel)
            {
                String path = dataModel.getPath();
                String oldPath = oldModel.getPath();
                boolean isFileChanged = (null != path && null != oldPath && !oldPath.equals(path));
                if (isFileChanged)
                    dataModel.setPath(new FileUtil().getUtil().moveFile(path, Constants.BASE_FILE_URL, false));
                dataDao.update(dataModel, uid);
                if (isFileChanged)
                    new File(oldPath).delete();
                if (checkRepeat(dataModel) > 1)
                {
                    dataDao.update(oldModel, 0);
                    return Ajax.fail().setMsg(FILE_EXIST);
                }
            }
            else
                result = Ajax.fail().setMsg(NOT_FOUND);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            result = Ajax.fail().setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 批量删除文件
     *
     * @param ids
     */
    public AjaxBean delete(long[] ids)
    {
        AjaxBean result;
        try
        {
            for (long id : ids)
            {
                DataModel model = dataDao.fetch(DataModel.class, id);
                if (null != model && null != model.getPath())
                {
                    File file = new File(model.getPath());
                    if (file.exists())
                        file.delete();
                }
                dataDao.delete(DataModel.class, id);
            }
            result = Ajax.ok();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            result = Ajax.fail().setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 删除文件
     *
     * @param id
     */
    public AjaxBean delete(long id)
    {
        AjaxBean result;
        try
        {
            DataModel model = dataDao.fetch(DataModel.class, id);
            if (null != model && null != model.getPath())
            {
                File file = new File(model.getPath());
                if (file.exists())
                    file.delete();
            }
            dataDao.delete(DataModel.class, id);
            result = Ajax.ok();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            result = Ajax.fail().setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 上传文件
     *
     * @param tempFile
     * @return
     */
    public AjaxBean uploadFile(TempFile tempFile)
    {
        AjaxBean result = Ajax.ok();
        try
        {
            if (null != tempFile)
                result = result.setData(new FileUtil().getUtil().uploadFile(tempFile, Constants.BASE_FILE_URL));
            else
                result = Ajax.fail().setMsg("文件上传失败！");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            result = Ajax.fail().setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 根据ID下载资料
     *
     * @param response
     * @param id
     * @return
     */
    public File download(HttpServletResponse response, long id)
    {
        response.setHeader("Accept-Ranges", "bytes");
        File result = null;
        DataModel dataModel = dataDao.fetch(DataModel.class, id);
        if (null != dataModel)
        {
            response.setHeader("Content-Disposition", "attachment;filename=" + dataModel.getName() + "." + dataModel.getSuffix());
            String path = dataModel.getPath();
            if (null != path)
                result = new File(path);
        }
        return result;
    }

    /**
     * 检查重复数据
     *
     * @param dataModel
     * @return
     * @throws Exception
     */
    private int checkRepeat(DataModel dataModel) throws Exception
    {
        int result = 0;
        Cnd cnd = Cnd.where("FILE_NAME", "=", dataModel.getName()).and(Cnd.exps("VERSION_NAME", "=", dataModel.getvName()).or("VERSION_CODE", "=", dataModel.getvCode()));
        List<DataModel> list = dataDao.query(DataModel.class, cnd);
        if (null != list)
            result = list.size();
        return result;
    }

    /**
     * 根据用户类型获取对应jsp页面
     *
     * @param user
     * @return
     *
     * Added By Zmt
     */
    public String getJsp(UserModel user, boolean isSearch)
    {
        String result;
        if (user.getType() == 3)
            result = "pages.back.data.data_preview";
        else{
            if (isSearch)
                result = "pages.back.data.data_list";
            else
                result = "pages.back.data.data";
        }
        return result;
    }

    /**
     * 获取DataQp
     *
     * @param qp
     * @return
     */
    public DataQp getDataQp(DataQp qp,UserModel user)
    {
        if (0 == qp.getPage())
            qp.setPage(1);
        qp.setRows(20);
        if(user.getType() == 3){
            qp.setRows(5);
        }
        return qp;
    }

    /**
     * 生成文件类型下拉框内容
     *
     * @return
     */
    public List<DropModel> getDataType()
    {
        return new ArrayList<DropModel>(){
            {
                add(new DropModel("APK", 0));
                add(new DropModel("DOC", 1));
                add(new DropModel("PDF", 2));
            }
        };
    }

}
